package com.sigmatrix.h5.service.common.upload;

import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.properties.FileWebProperties;

import so.sao.file.datastore.exception.FileDatastoreException;
import so.sao.file.datastore.service.FileService;
import sun.misc.BASE64Decoder;

/**
 * 
 * @author wei.wang
 *
 */
@Service
public class UploadService {

	@Autowired
	private FileWebProperties applicationProperties;

	@Autowired
	private FileService fileService;

	public List<String> imageConvertAndUpload(Base64ImageUploadRequest imageUploadRequest, String esecode,
			String prefix) throws IOException {

		List<String> cdnUrlList = new ArrayList<>();

		for (Base64ImageUpload imageUpload : imageUploadRequest.getImages()) {
			String imageStr = imageUpload.getImageJson();
			String[] imageArr = imageStr.split(";base64,");

			if (imageArr.length == 3) {
				BASE64Decoder decoder = new BASE64Decoder();
				byte[] imageBuffer = decoder.decodeBuffer(imageArr[1]);
				for (int i = 0; i < imageBuffer.length; i++) {
					if (imageBuffer[i] < 0) {
						// 调整异常数据
						imageBuffer[i] += 256;
					}
				}

				String contentType = imageArr[0].substring(imageArr[0].indexOf(":") + 1);
				String imageSuffix = imageArr[0].split("/")[1];

				String objectPath = "/" + esecode + "/";
				String fileName = formatUploadFileName();
				String filePath = new StringBuilder(prefix).append(objectPath).append(fileName).append(".")
						.append(imageSuffix).toString();

				try {
					fileService.upload(applicationProperties.getDefaultContainerName(), imageBuffer, filePath,
							contentType);
				} catch (FileDatastoreException e) {
					throw new MessageException("文件上传失败", e);
				}

				String cdnUrl = new StringBuilder(applicationProperties.getCdnHost())
						.append(applicationProperties.getDefaultContainerName()).append("/").append(filePath)
						.toString();

				cdnUrlList.add(cdnUrl);
			} else {
				throw new MessageException("文件格式错误");
			}
		}
		return cdnUrlList;
	}

	public List<String> imageFileUpload(MultipartFile file, String esecode, String prefix){
		List<String> cdnUrlList = new ArrayList<>();
		// 判断文件类型
		// String contentType = file.getContentType();
		// long fileSize = file.getSize();

		String objectPath = "/" + esecode + "/";
		String fileName = file.getOriginalFilename();
		fileName = fileName.substring(fileName.lastIndexOf("."));// 后缀
		String filePath = new StringBuilder(prefix).append(objectPath).append(formatUploadFileName()).append(fileName)
				.toString();
		try {
			fileService.upload(applicationProperties.getDefaultContainerName(), file.getBytes(), filePath,
					file.getContentType());
			// 上传后的cdn +filePath ==》 url地址
			String url = new StringBuilder(applicationProperties.getCdnHost())
					.append(applicationProperties.getDefaultContainerName()).append("/").append(filePath).toString();
			cdnUrlList.add(url);
		} catch (Exception e) {
			throw new MessageException("文件上传错误", e);
		}
		return cdnUrlList;
	}

	private String formatUploadFileName() {
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
		ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("GMT+8"));
		return zonedDateTime.format(dateTimeFormatter) + "-" + (int) (Math.random() * 10000);
	}

}